package com.itheima.web;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @outhor
 * @date 2020/1/15 16:39
 */

@RequestMapping("ordersetting")
@RestController
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    @RequestMapping("setNumberByDate")
    public Result setNumberByDate(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.setNumberByDate(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }

    @RequestMapping("findOrderSettingByMonth")
    public Result findOrderSettingByMonth(@RequestBody Map map) {
        try {
            String date = (String) map.get("date");
            List<Map> orderSettingList = orderSettingService.findOrderSettingByMonth(date);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettingList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @RequestMapping("upload")
    public Result upload(MultipartFile excelFile) {
        try {
            List<String[]> datas = POIUtils.readExcel(excelFile);
            List<OrderSetting> orderSettings = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(datas)) {
                for (String[] row : datas) {
                    if (row.length != 2) {
                        continue;
                    }
                    String dateStr = row[0];
                    String nuberStr = row[1];
                    OrderSetting orderSetting = new OrderSetting(DateUtil.parse(dateStr, "yyyy/MM/dd"), Integer.valueOf(nuberStr));
                    orderSettings.add(orderSetting);
                }
            }
            orderSettingService.batchSaving(orderSettings);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }
}
